package com.cw.jeeyt.controller.system;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cw.jeeyt.api.dto.response.JsonResultDto;
import com.cw.jeeyt.common.DataTable;
import com.cw.jeeyt.common.ResultData;
import com.cw.lang.common.utils.IdGenerator;
import com.cw.jeeyt.common.enums.EnumOperateFlag;
import com.cw.jeeyt.common.web.BaseController;
import com.cw.jeeyt.service.bo.system.SystemAttachBo;
import com.cw.jeeyt.service.directive.PageDictDirective;
import com.cw.jeeyt.service.directive.PermissionDirective;
import com.cw.jeeyt.service.intf.system.SystemAttachService;
import com.cw.jeeyt.service.utils.FileTools;
import com.cw.lang.common.utils.CollectionUtil;
import com.cw.lang.mybatis.dto.PageInfo;

/**
 * 附件信息控制层
 *
  * @author chenw
 * @version 1.0.0
 */
@Controller
@RequestMapping("/systemAttach")
public class SystemAttachController extends BaseController {
    @Resource
    private SystemAttachService systemAttachService;

    /**
     * 跳转到附件信息列表查询页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/")
    public ModelAndView to_attach() {
        ModelAndView mv = new ModelAndView("system/systemAttach_index");
        return mv;
    }

    /**
     * 跳转到附件信息列表查询页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/query")
    public ModelAndView query() throws Exception {
        ModelAndView mv = new ModelAndView("system/systemAttach_index");
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable 请求数据
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listSystemAttach")
    public ResultData listSystemAttach(@RequestBody DataTable dataTable) throws Exception {

        SystemAttachBo systemAttachBo = JSONObject.parseObject(JSON.toJSONString(dataTable.getQueryCond()),
            SystemAttachBo.class);
        if (systemAttachBo == null) {
            systemAttachBo = new SystemAttachBo();
        }
        PageInfo<SystemAttachBo> pageInfo = systemAttachService.queryByPage(systemAttachBo, dataTable.getStart(),
            dataTable.getLength());
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }

    /**
     * 跳转到附件信息表单页面
     *
     * @param id 主键
     * @param operation 操作  add 新增 edit修改 view查看
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-form")
    public ModelAndView editForm(String id, String operation) throws Exception {

        ModelAndView mv = new ModelAndView("system/systemAttach_form");
        SystemAttachBo systemAttachBo = null;
        List<SystemAttachBo> systemAttachList = null;
        if (EnumOperateFlag.ADD.getCode()
            .equals(operation)) {
            systemAttachList = new ArrayList<>();
            systemAttachBo = new SystemAttachBo();
            id = IdGenerator.nextStrId();
            systemAttachBo.setId(id);
        } else {
            systemAttachBo = systemAttachService.getSystemAttachById(id);
            // 附件列表(如果存在附件)
            systemAttachList = systemAttachService.getAttachListByObjectId(id);
        }
        mv.addObject("systemAttachList", systemAttachList);
        mv.addObject("systemAttach", systemAttachBo);
        mv.addObject("operation", operation);
        mv.addObject("id", id);
        mv.addObject("PageDict", new PageDictDirective());
        return mv;
    }

    /**
     * 根据操作类型保存附件信息数据
     *
     * @param systemAttachBo
     * @param operation add 新增  edit 修改
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/saveSystemAttach", method = RequestMethod.POST)
    public JsonResultDto saveSystemAttach(SystemAttachBo systemAttachBo, String operation) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            if (operation.equals(EnumOperateFlag.ADD.getCode())) {
                systemAttachService.insert(systemAttachBo);
            } else if (operation.equals(EnumOperateFlag.EDIT.getCode())) {
                systemAttachService.update(systemAttachBo);
            }
            jsonResultDto.setMsg("保存成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("保存失败:" + e.getMessage());

        }
        return jsonResultDto;
    }

    /**
     * 删除附件信息
     *
     * @param systemAttachBo
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public JsonResultDto delete(SystemAttachBo systemAttachBo) throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            systemAttachService.delete(systemAttachBo);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResultDto.setMsg("删除失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 删除附件信息
     *
     * @param objectId
     * @throws Exception
     */
    @RequestMapping(value = "/deleteAttachRelation")
    @ResponseBody
    public JsonResultDto deleteAttachRelation(String objectId, String attachId) throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            systemAttachService.deleteAttachRelation(objectId, attachId);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {

            jsonResultDto.setMsg("删除失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 上传附件到特定的目录及数据库
     *
     * @param modelMap
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadAttachToDirAndDb")
    public void processUploadDirAndDb(ModelMap modelMap, MultipartHttpServletRequest request, PrintWriter writer)
    throws Exception {
        String attachIds = "";
        Map<String, MultipartFile> fileMap = request.getFileMap();
        String path = request.getSession()
            .getServletContext()
            .getRealPath("/");
        System.err.println("path:" + path);
        attachIds = systemAttachService.uploadAttachToDirectoryAndDb(fileMap, path);
        writer.write(attachIds.toString());
    }

    /**
     * 下载附件
     *
     * @param response
     * @param attachId
     */
    @RequestMapping("/downloadAttach")
    public void dowmloadAttach(HttpServletResponse response, String attachId)
    throws Exception {
        SystemAttachBo systemAttachBo = systemAttachService.getSystemAttachById(attachId);
        try {
            FileTools.downloadFile(response, systemAttachBo);
        } catch (Exception e) {
            logger.error("下载内容附件出错：" + e.getMessage());
        }
    }

}
